package org.newlifecac;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SMSSender extends Activity implements OnClickListener
{
	private Button btnSend;
	private Button btnback;
	private Button btnclear;
	private Button btn1StDate;
	private Button btnbapDate;
	
	private EditText et_name;
	private EditText et_cell;
	private EditText et_addr1;
	private EditText et_addr2;
	private EditText et_city;
	private EditText et_zipcode;
	private EditText et_memo;
	
	
	private String nameString;
	private String cellString;
	private String addr1String;
	private String addr2String;
	private String cityString;
	private String zipcodeString;
	private String memoString;
	private String gendersString;
	private String stdayString;
	private String bapdayString;
	private String content;
	
	private RadioButton male;
	private RadioButton female;
	
	private ImageButton btn_back;
	private ImageButton btn_next;
	
	
	private Calendar cal = Calendar.getInstance();
	private AlertDialog.Builder dialog;
	private DBService dbService;
	
	// about state button
		private Button btn_state;
		private Button btn_states_dialog_ok, btn_states_dialog_cancel,
				btn_states_dialog_search;
		private ListView lv_states_dialog_list;
		private List<States> listStates;
		private StateAdapter stateAdapter;
		private EditText et_states_dialog_search;
		private ArrayList<HashMap<String, Object>> listitemstate;
		private Dialog stateDialog;
		// ---end---
	
		private static String SD_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
		public static File PIC_PATH = new File(SD_PATH + "/Picture/");
		public static File CONFIG_PATH = new File(SD_PATH + "/Newlifecac/");
		public static File CONFIG_FILE = new File(CONFIG_PATH+"/message.properties");
		public static String phoneString = "";
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.smsmain);
		dbService = new DBService(SMSSender.this);

		btnSend = (Button) findViewById(R.id.btnSend);
		btnback = (Button) findViewById(R.id.btnback);
		btnclear = (Button) findViewById(R.id.btnclear);
		btn1StDate = (Button) findViewById(R.id.btn1StDate);
		btnbapDate = (Button) findViewById(R.id.btnbapDate);
		btn_state  = (Button) findViewById(R.id.btn_state);
		
		btnSend.setOnClickListener(this);
		btnback.setOnClickListener(this);
		btnclear.setOnClickListener(this);
		btn1StDate.setOnClickListener(this);
		btnbapDate.setOnClickListener(this);
		btn_state.setOnClickListener(this);
		
		et_name  = (EditText) findViewById(R.id.et_name);
		et_cell = (EditText) findViewById(R.id.et_cell);
		et_addr1 = (EditText) findViewById(R.id.et_addr1);
		et_addr2 = (EditText) findViewById(R.id.et_addr2);
		et_city = (EditText) findViewById(R.id.et_city);
		et_zipcode = (EditText) findViewById(R.id.et_zipcode);
		et_memo = (EditText) findViewById(R.id.et_memo);
		
		male = (RadioButton) findViewById(R.id.male);
		female = (RadioButton) findViewById(R.id.female);
		
		/*btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_next = (ImageButton) findViewById(R.id.btn_next);
		*/
		male.setOnCheckedChangeListener(radioListener);
		female.setOnCheckedChangeListener(radioListener);
		male.setChecked(true);
		
		initFields();

	}
	
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.btnSend:
			send("填写的信息正确吗?",getContent());
			break;
		case R.id.btnback:
			onKeyDown(KeyEvent.KEYCODE_BACK, null);
			break;
		case R.id.btnclear:
			initFields();
			break;
		case R.id.btn1StDate:
			new DatePickerDialog(SMSSender.this, datelistener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
			break;
		case R.id.btnbapDate:
			new DatePickerDialog(SMSSender.this, datelistener1, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
			break;
		case R.id.btn_state:
			StateDialogWindow();
			break;
		}

	}
	
	public void StateDialogWindow()
	{
		bindStateData();
		if (stateDialog == null)
		{
			stateDialog = new Dialog(this, R.style.Transparent_dialog);
			stateDialog.setContentView(R.layout.dialog_perview_states);
		}
		lv_states_dialog_list = (ListView) stateDialog
				.findViewById(R.id.lv_states_dialog_list);
		btn_states_dialog_ok = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_ok);
		btn_states_dialog_cancel = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_cancel);
		btn_states_dialog_search = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_search);
		et_states_dialog_search = (EditText) stateDialog
				.findViewById(R.id.et_states_dialog_search);

		btn_states_dialog_ok.setOnClickListener(OnClickDialogWindowListener);
		btn_states_dialog_cancel.setOnClickListener(OnClickDialogWindowListener);
		btn_states_dialog_search.setOnClickListener(OnClickDialogWindowListener);
		lv_states_dialog_list.setOnItemClickListener(onItemClickDialogWindowListener);
				
		int size = listStates.size();
		if (stateAdapter == null) {
			stateAdapter = new StateAdapter(this, listStates);
			lv_states_dialog_list.setAdapter(stateAdapter);
		} else {
			stateAdapter.setSource(listStates);
			stateAdapter.notifyDataSetChanged();
		}
		
		String stateString = btn_state.getText().toString().trim();
		if (stateString.equals(""))
		{
			stateAdapter.ScrollToRow(0);
			lv_states_dialog_list.setSelection(0);
		} else
		{
			for (int i = 0; i < listStates.size(); i++)
			{
				if (stateString.equals(listStates.get(i).getState_id()))
				{
					stateAdapter.ScrollToRow(i);
					lv_states_dialog_list.setSelection(i);
				}
			}
		}
		stateDialog.show();
	}

	public OnClickListener OnClickDialogWindowListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			switch (v.getId())
			{
			case R.id.btn_states_dialog_ok:
				if (listStates.size() > 0)
				{
					btn_state.setText(listStates.get(
							stateAdapter.GetSelectedIndex()).getState_id());
				}
				stateDialog.dismiss();
				break;
			case R.id.btn_states_dialog_cancel:
				stateDialog.dismiss();
				break;
			case R.id.btn_states_dialog_search:
				String searchStates = et_states_dialog_search.getText().toString();
				listStates = dbService.getStatesById(searchStates);
				stateAdapter.setSource(listStates);
				stateAdapter.notifyDataSetChanged();
				stateAdapter.ScrollToRow(0);
				et_states_dialog_search.setText("");
				break;
			}
		}
	};
	
	public OnItemClickListener onItemClickDialogWindowListener = new OnItemClickListener()
	{
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			switch (parent.getId())
			{
			case R.id.lv_states_dialog_list:
				stateAdapter.ScrollToRow(position);
				break;
			default:
				break;
			}

		}
	};

	public void bindStateData()
	{
		listStates = dbService.getStates();
	}
	
	public void send(String title, String message)
	{
		
		
		dialog = new AlertDialog.Builder(SMSSender.this);
		dialog.setTitle(title).setIcon(android.R.drawable.ic_dialog_info)
				.setMessage(message)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						sendMessage();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.cancel();
					}
				}).create().show();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK )
		{
			Intent intent = new Intent();
			intent.setClass(SMSSender.this, FilePickerActivity.class);
			startActivity(intent);
			SMSSender.this.finish();
		}
		return false;
	}
	
	
	private DatePickerDialog.OnDateSetListener datelistener = new DatePickerDialog.OnDateSetListener()
	{
		public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3)
		{
			cal.set(Calendar.YEAR, arg1);
			cal.set(Calendar.MONTH, arg2);
			cal.set(Calendar.DAY_OF_MONTH, arg3);
			update1stDate();
		}
	};
	
	private void update1stDate()
	{
		SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
		btn1StDate.setText(df.format(cal.getTime()));
	}
	
	private DatePickerDialog.OnDateSetListener datelistener1 = new DatePickerDialog.OnDateSetListener()
	{
		public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3)
		{
			cal.set(Calendar.YEAR, arg1);
			cal.set(Calendar.MONTH, arg2);
			cal.set(Calendar.DAY_OF_MONTH, arg3);
			updateBapDate();
		}
	};
	
	private void updateBapDate()
	{
		SimpleDateFormat df1 = new SimpleDateFormat("MM-dd-yyyy");
		btnbapDate.setText(df1.format(cal.getTime()));
	}
	
	public void sendMessage()
	{
		nameString = et_name.getText().toString().trim();
		cellString = et_cell.getText().toString().trim();
		addr1String = et_addr1.getText().toString().trim();
		addr2String = et_addr2.getText().toString().trim();
		cityString = et_city.getText().toString().trim();
		zipcodeString = et_zipcode.getText().toString().trim();
		memoString = et_memo.getText().toString().trim();
		
		
		
		SmsManager smsManager = SmsManager.getDefault();

		try
		{
			PendingIntent mPI = PendingIntent.getBroadcast(
					SMSSender.this, 0, new Intent(), 0);
			smsManager.sendTextMessage(phoneString, null, getContent(), mPI, null);
		} catch (Exception e)
		{
			// TODO: handle exception
		}

		Toast.makeText(SMSSender.this, "Done!/发送成功!!", Toast.LENGTH_SHORT)
				.show();

		
	}
	
	public void initFields()
	{
		et_name.setText("");
		et_cell.setText("");
		et_addr1.setText("");
		et_addr2.setText("");
		et_city.setText("");
		et_zipcode.setText("");
		et_memo.setText("");
		male.setChecked(true);
		female.setChecked(false);
	}
	
	private OnCheckedChangeListener radioListener = new OnCheckedChangeListener()
	{
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked)
		{
			RadioButton rbtn = (RadioButton) buttonView;
			switch (rbtn.getId())
			{
			case R.id.male:
				if (isChecked)
				{
					male.setChecked(true);
					female.setChecked(false);
				}
				break;
			case R.id.female:
				if (isChecked)
				{
					male.setChecked(false);
					female.setChecked(true);
				}
				break;
			}

		}
	};
	
	public void Toast(String str)
	{
		Toast.makeText(SMSSender.this, str, Toast.LENGTH_LONG).show();
	}
	
	public void Keyboard()
	{
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(SMSSender.this.getCurrentFocus()
				.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	@Override
	protected void onDestroy()
	{
		if (dbService != null)
		{
			dbService.closeDB();
		}
		super.onDestroy();
	}
	
	public String getContent()
	{
		nameString = et_name.getText().toString().trim();
		cellString = et_cell.getText().toString().trim();
		addr1String = et_addr1.getText().toString().trim();
		addr2String = et_addr2.getText().toString().trim();
		cityString = et_city.getText().toString().trim();
		zipcodeString = et_zipcode.getText().toString().trim();
		memoString = et_memo.getText().toString().trim();
		stdayString = btn1StDate.getText().toString().trim();
		bapdayString = btnbapDate.getText().toString().trim();
		if (male.isChecked())
			gendersString = "男";
		else
			gendersString = "女";
		
		if (!CONFIG_FILE.exists())
		{
			phoneString = "17182106381";
		}else 
		{
			BackupSetting bSetting = new BackupSetting();
			System.out.println("Configuration Path-->"+CONFIG_FILE);
			Properties pro = bSetting.loadConfig(this,CONFIG_FILE+"");
			phoneString = (String) pro.get("phone");
		}
		content = "发送给:"+phoneString+ "\r\n"
		+"姓名:"+nameString+"\r\n"
		+"性别:"+gendersString+"\r\n"
		+"电话:"+cellString+"\r\n"
		+"第一次来教会:"+stdayString+"\r\n"
		+"受洗日:"+bapdayString+"\r\n"
		+"教会服事项目:"+memoString+"\r\n";
		
		return content;
	}

}
